package com.xci.platform.web.configuration;

import com.xci.platform.helper.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;

/**
 * Redis缓存配置
 */
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

    // @Value("${spring.cache}")
    // public CacheProperties properties;

    @Autowired
    private Environment env;

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(".");
                sb.append(method.getName());
                if (params.length > 0) {
                    sb.append(",");
                    for (Object obj : params) {
                        sb.append(obj.toString());
                    }
                }
                return sb.toString();
            }
        };
    }


    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {

        String type = env.getProperty("spring.cache.type");
        if (StringHelper.isNotBlank(type) && type.equalsIgnoreCase("redis")) {
            RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                    .RedisCacheManagerBuilder
                    .fromConnectionFactory(factory)
                    .cacheDefaults(RedisCacheConfiguration
                            .defaultCacheConfig()
                            .disableCachingNullValues()
                            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(getStringRedisSerializer()))
                            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getGenericJackson2JsonRedisSerializer()))
                            .entryTtl(Duration.ofMinutes(10)));
            return builder.build();
        } else {
            net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("es");
            if (cacheManager == null) {
                EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
                String path = env.getProperty("spring.cache.ehcache.config");
                if (path != null) {
                    cacheManagerFactoryBean.setConfigLocation(new ClassPathResource(path));
                }
                cacheManagerFactoryBean.setShared(true);
                cacheManager = cacheManagerFactoryBean.getObject();
            }
            return new EhCacheCacheManager(cacheManager);
        }

        //对每个缓存空间设置过期时间
        /*
        RedisCacheConfiguration cacheConfiguration =RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1))//缓存1天
                .disableCachingNullValues().computePrefixWith(cacheName -> "miaosha1".concat(":").concat(cacheName).concat(":"))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                        GenericJackson2JsonRedisSerializer()));
        // 设置一个初始化的缓存空间set集合
        Set<String> cacheNames =  new HashSet<>();
        cacheNames.add("my-redis-cache1");
        cacheNames.add("user");

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("my-redis-cache1", cacheConfiguration);
        configMap.put("user", cacheConfiguration.entryTtl(Duration.ofSeconds(120)));
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)     // 使用自定义的缓存配置初始化一个cacheManager
                .initialCacheNames(cacheNames)  // 注意这两句的调用顺序，一定要先调用该方法设置初始化的缓存名，再初始化相关的配置
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
        */
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setDefaultSerializer(getGenericJackson2JsonRedisSerializer());
        StringRedisSerializer stringRedisSerializer = getStringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        return redisTemplate;
    }

    @Bean
    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

    @Bean
    public StringRedisSerializer getStringRedisSerializer() {
        return new StringRedisSerializer();
    }
}
